package com.inspur.dgov.vlbod.http;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * @author Liu Dongyang
 */
@Getter
@Setter
public class DgovResponse<T> implements Serializable {

    public static final int FAILURE = 0;

    public static final int SUCCESS = 1;

    public static final String SUCCESS_MSG = "success";

    private static final long serialVersionUID = 8116851891072095420L;

    /**
     * 结果码［0失败 1成功］
     */
    private int code;

    /**
     * HTTP响应码默认200
     */
    private int status;

    /**
     * 提示消息
     */
    private String message;

    /**
     * 数据清单
     */
    private T data;

    private DgovResponse(int code, int status, String message, T data) {
        this.code = code;
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public static <D> DgovResponse<D> success() {
        return new DgovResponse<>(SUCCESS, HttpStatus.HTTP_OK, SUCCESS_MSG, null);
    }

    public static <D> DgovResponse<D> success(D data) {
        return new DgovResponse<>(SUCCESS, HttpStatus.HTTP_OK, SUCCESS_MSG, data);
    }

    public static <D> DgovResponse<D> success(String message, D data) {
        return new DgovResponse<>(SUCCESS, HttpStatus.HTTP_OK, message, data);
    }

    public static DgovResponse<Object> fail(Exception e) {
        return new DgovResponse<>(FAILURE, HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage(), null);
    }

    public static DgovResponse<Object> failAndDetail(Exception e) {
        return new DgovResponse<>(FAILURE, HttpStatus.HTTP_INTERNAL_ERROR, ExceptionUtil.stacktraceToString(e), null);
    }

    public static DgovResponse<Object> fail(int status, String message) {
        return new DgovResponse<>(FAILURE, status, message, null);
    }

    public static DgovResponse<Object> fail(String message) {
        return new DgovResponse<>(FAILURE, HttpStatus.HTTP_INTERNAL_ERROR, message, null);
    }

    /**
     * 带消息的失败响应
     * @param message
     * @param httpStatus
     * @return
     */
    public static DgovResponse<Object> fail(String message, int httpStatus) {
        return new DgovResponse<>(FAILURE, httpStatus, message, null);
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    public String toString(boolean needRaw) {
        if (needRaw)
            return super.toString();
        else
            return this.toString();
    }
}

